'******************************************************
' Copy to/expand from zip folder through windows shell
'******************************************************

Dim retCode : retCode = 1

If WScript.Arguments.Count < 3 Then
	WScript.Echo "Usage: wshzip <copy|expand> <zipfolder> <file1> [<file2>...]"
	WScript.Quit
End If

Dim inFiles : inFiles = Array()
Dim i, j

If StrComp(WScript.Arguments(0), "copy") = 0 Then
	For i = 2 To WScript.Arguments.Count - 1
		j = UBound(inFiles)
		ReDim Preserve inFiles(j + 1)
		inFiles(j + 1) = WScript.Arguments(i)
	Next
	ZipTargets inFiles, WScript.Arguments(1)
ElseIf StrComp(WScript.Arguments(0), "expand") = 0 Then
	UnzipTarget WScript.Arguments(2), WScript.Arguments(1)
Else
	WScript.Echo "unknown command - " & WScript.Arguments(0)
End If

WScript.Quit retCode

Function ZipTargets(targetPaths, zipFile)

	Dim objApp, objFSO, objTxt, objZip, fileCount, absPath

	Const ForWriting = 2

	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objTxt = objFSO.OpenTextFile(zipFile, ForWriting, True)
	objTxt.Write "PK" & Chr(5) & Chr(6) & String(18, Chr(0))
	objTxt.Close
	Set objTxt = Nothing

	Set objApp = CreateObject("Shell.Application")

	absPath = objFSO.GetAbsolutePathName(zipFile)
	Set objZip = objApp.NameSpace(absPath)

	fileCount = 0

	For Each pathEntry In targetPaths
		If objFSO.FileExists(pathEntry) Then
			absPath = objFSO.GetAbsolutePathName(pathEntry)
			objZip.CopyHere absPath, 4
			fileCount = fileCount + 1
		ElseIf objFSO.FolderExists(pathEntry) Then
			absPath = objFSO.GetAbsolutePathName(pathEntry)
			objZip.CopyHere absPath, 4
			fileCount = fileCount + 1
		Else
			WScript.Echo pathEntry & " - path not found"
		End If
	Next

	Do While objZip.Items.Count < fileCount
		WScript.Sleep 200
	Loop

	Set objZip = Nothing
	Set absPath = Nothing
	Set objApp = Nothing
	Set objFSO = Nothing

End Function

Function UnzipTarget(outPath, zipFile)

	Dim objApp, objFSO, objZip, absPath, objOut

	Set objFSO = CreateObject("Scripting.FileSystemObject")

	If Not objFSO.FolderExists(outPath) Then
		absPath = objFSO.GetAbsolutePathName(outPath)
		objFSO.CreateFolder(absPath)
	End If

	Set objApp = CreateObject("Shell.Application")

	absPath = objFSO.GetAbsolutePathName(zipFile)
	Set objZip = objApp.NameSpace(absPath).Items()

	absPath = objFSO.GetAbsolutePathName(outPath)
	Set objOut = objApp.NameSpace(absPath)

	objOut.CopyHere objZip, 4

	Set objZip = Nothing
	Set absPath = Nothing
	Set objOut = Nothing
	Set objApp = Nothing
	Set objFSO = Nothing

End Function
